package org.example.springboot.jpa.controller;

import org.example.springboot.jpa.po.User;
import org.example.springboot.jpa.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.annotation.Resource;
import java.util.Map;

@Controller
@SessionAttributes("myUser") // 表示session对象的key为myUser
public class UserController {

    @Resource
    private UserService userService;


    @RequestMapping("/")
    public String toMain(Map<String, Object> map) {
        // 从session中获取用户信息，如果不存在，则跳转：/login，让用户登录
        Object myUser = map.get("myUser");
        if (myUser == null) {
            // return "login";
            return "redirect:/login";
        }
        return "main";
    }

    @GetMapping("/login")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/login")
    public String login (String username, String password, Map<String, Object> map) {
        User user = userService.authenticate(username, password);
        if (user != null) {
            map.put("myUser", user);
            return "redirect:/";
        }
        return "login";
    }
}
